import WechatJSSDK from 'wechat-jssdk/dist/client.umd';
import request from '../http';
import { urlParse } from '../utils';
import store from '../store';
import { MP_APP_ID } from '../config';

export function initWechat(top, url = 'http://h5.lantingshucheng.com') {
  // 微信配置
  const config = { debug: true };
  // 获取微信签名信息并初始化
  request({
    method: 'GET',
    url: '/api/wechat/get-signature',
    data: {
      url: encodeURIComponent(url)
    },
    needAuth: false,
    skipToast: false,
    errorText: '获取微信签名失败'
  })
    .then(res => {
      if (res.ok) {
        config.appId = res.data.appId;
        config.nonceStr = res.data.nonceStr;
        config.signature = res.data.signature;
        config.timestamp = res.data.timestamp;
        config.jsApiList = [
          'hideMenuItems',
          'onMenuShareTimeline',
          'chooseCard',
          'addCard',
          'openCard',
          'chooseWXPay'
          // 'updateAppMessageShareData',
          // 'updateTimelineShareData',
        ];
        top.$wechat = new WechatJSSDK(config);
        top.$wechat
          .initialize()
          .then(wx => {
            console.log(wx.oauth.snsUserInfoUrl);
          })
          .catch(err => {
            console.log(err);
            uni.showToast({ title: '微信初始化失败', icon: 'none' });
          });
      }
    })
    .catch(err => {
      console.log(err);
      uni.showToast({ title: '微信初始化失败', icon: 'none' });
    });
}

// 微信公众号授权
export function wxAuthorize(url) {
  const link = url || window.location.href;
  const params = urlParse(link); // 地址解析

  // 已经授权登录过的就不用再授权了
  if (store.getters.token) return;

  // 如果拿到code，调用授权接口，没有拿到就跳转微信授权链接获取
  if (params.code) {
    wxAuth(params.code);
  } else {
    let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${MP_APP_ID}&redirect_uri=${encodeURIComponent(link)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
    window.location.href = authURL;
  }
}

// 获取用户信息
export function wxAuth(code) {
  request({
    method: 'POST',
    url: '/api/front/user/login',
    data: {
      wey: 'mp-account',
      code
    },
    needAuth: false,
    skipToast: false,
    errorText: '微信登录失败'
  }).then(res => {
    store.commit('login', {
      cache: true,
      token: res.token,
      userInfo: res.userInfo
    });
  });
}
